package com.flyaudio.xiaopengautopilot.view;

import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.flyaudio.xiaopengautopilot.R;
import com.flyaudio.xiaopengautopilot.custom.FlyBarChart;
import com.flyaudio.xiaopengautopilot.presenter.IVehicleModule;
import com.flyaudio.xiaopengautopilot.util.AndroidDpConvert;
import com.flyaudio.xiaopengautopilot.util.CalendarHandler;
import com.flyaudio.xiaopengautopilot.util.L;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;

import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.utils.Fill;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class PowerConsumptionBarChart implements View.OnClickListener {
    private final String TAG = "PowerConsumptionBarChart";

    private final Context context;
    private final FlyBarChart barChart;
    private final CalendarHandler calendarHandler = new CalendarHandler();
    private final TextView tv_power_consumption_month;
    private final TextView tv_power_consumption_year;
    private final TextView tv_power_consumption_time;
    private final Button bt_power_consumption_prev;
    private final Button bt_power_consumption_next;

    private BarChartHanlder curhBar = null;
    private final int MONTH_BAR = 0;
    private final int YEAR_BAR = 1;
    public View getView() {
        return v;
    }
    private boolean monthOrYear = true;
    private final View v;

    public PowerConsumptionBarChart(Context context){
        this.context = context;
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = inflater.inflate(R.layout.view_power_consumpt_barchart, null);
        barChart = v.findViewById(R.id.power_consumption_chart);
        tv_power_consumption_month = v.findViewById(R.id.tv_power_consumption_month);
        tv_power_consumption_year = v.findViewById(R.id.tv_power_consumption_year);
        tv_power_consumption_time = v.findViewById(R.id.tv_power_consumption_time);
        bt_power_consumption_prev = v.findViewById(R.id.bt_power_consumption_prev);
        bt_power_consumption_next = v.findViewById(R.id.bt_power_consumption_next);
        bt_power_consumption_next.setOnClickListener(this);
        bt_power_consumption_prev.setOnClickListener(this);
        tv_power_consumption_month.setOnClickListener(this);
        tv_power_consumption_year.setOnClickListener(this);
        barChart.initChartGestureListener();
        initMouthView();

    }

    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            case R.id.tv_power_consumption_month:
                if (curhBar.barID != MONTH_BAR){
                    initMouthView();
                }

                break;
            case R.id.tv_power_consumption_year:
                if (curhBar.barID != YEAR_BAR){
                    initYearView();
                }

                break;
            case R.id.bt_power_consumption_next:
                curhBar.pageNext();
                break;
            case R.id.bt_power_consumption_prev:
                curhBar.pagePrev();
                break;
            default:
                break;
        }
    }

    private  interface IBarCharHandler{
       void initView(int dataSize);
       void pageNext();
       void pagePrev();
    }
    private abstract class BarChartHanlder implements IBarCharHandler{
        int barID = 0;
        float barWidth = 0f;
        ValueFormatter xValueFormatter = null;
        ValueFormatter yVvalueFormatter = null;
        int labelCount = 6;
        int dataSize = 0;
        int countOnePage = 0;
        float pxBar = 14f;
        float ymin = 0;
        float yMax = 0;
        int itemIndex = 0;
        float computeBarWidth(float pxBar,float pxXWidth,int count)
        {
            return pxBar*count/pxXWidth;
        }
        BarChartHanlder(int barID)
        {
            this.barID = barID;
        }
        void setData(List<BarEntry> list) {

            BarDataSet lineDataSet = new BarDataSet(list, "");
            setLine(lineDataSet);
            BarData data = new BarData(lineDataSet);
            data.setBarWidth(barWidth);
            //设置数据
            barChart.setData(data);
            barChart.notifyDataSetChanged();//刷新数据
            barChart.invalidate();//重绘
        }
        void setLine(BarDataSet set) {

            set.setAxisDependency(YAxis.AxisDependency.RIGHT);
            //设置线条的颜色
            List<Fill> gradientFills = new ArrayList<>();
            gradientFills.add(new Fill(context.getResources().getDrawable(R.drawable.barchar_fillet_column)));
            set.setFills(gradientFills);
            set.setHighlightEnabled(false);
            //设置字体大小
            set.setValueTextSize(AndroidDpConvert.px2dip(context,10f));
            set.setDrawValues(false);
//        set.setFillDrawable(context.getResources().getDrawable(R.drawable.fold_line_fill_bg));
            //设置是否填充
//        set.setDrawFilled(true);
        }
        void initX()
        {
            //设置x轴网格线
            XAxis xAxis=barChart.getXAxis();
            //设置坐标间隔
            xAxis.setAxisMinimum(0-barWidth/2);//设置离左边位置0.5个柱状图的宽度
            xAxis.setAxisMaximum((dataSize-1) + barWidth/2);//设置总的宽度，左右各空0.5个柱状图的宽度
            //        //设置x轴标签数，默认为6个
            xAxis.setLabelCount(labelCount,false);
            //x轴
            xAxis.setValueFormatter(xValueFormatter);
            xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
            xAxis.setXOffset(0);
            xAxis.setYOffset(AndroidDpConvert.px2dip(context,23f));
            xAxis.setTextSize(AndroidDpConvert.px2dip(context,16f));
            xAxis.setTextColor(Color.parseColor("#FFFFFF"));
            xAxis.setDrawAxisLine(true);
            xAxis.setAxisLineWidth(AndroidDpConvert.px2dip(context,1f));
            xAxis.setAxisLineColor(Color.parseColor("#66FFFFFF"));
            xAxis.setGranularityEnabled(true);
            xAxis.setGranularity(1f);
            xAxis.setDrawGridLines(false);  //不画网格线
            xAxis.setEnabled(true);
        }
        void initY()
        {
            barChart.getAxisLeft().setEnabled(false);
            YAxis yAxisR = barChart.getAxisRight();;
            //设置坐标间隔
            yAxisR.setAxisMaximum(yMax);
            yAxisR.setAxisMinimum(ymin);
            //x轴
            yAxisR.setValueFormatter(yVvalueFormatter);
            yAxisR.setDrawGridLines(true);
            yAxisR.setDrawAxisLine(false);
            yAxisR.setLabelCount(6,true);
            yAxisR.setXOffset(AndroidDpConvert.px2dip(context,31f));
            yAxisR.setYOffset(0);
            yAxisR.setGridColor(Color.parseColor("#1ED4716E"));
            yAxisR.setGridLineWidth(AndroidDpConvert.px2dip(context,1f));
            yAxisR.setTextSize(AndroidDpConvert.px2dip(context,16f));
            yAxisR.setTextColor(Color.parseColor("#FFFFFF"));
        }
        void initBarChar()
        {
            barChart.setViewPortOffsets(49f,28f,97f,60f);
            //隐藏图表右下角显示内容
            Description description = new Description();
            description.setEnabled(false);
            barChart.setNestedScrollingEnabled(false);
            barChart.setDescription(description);
            barChart.setScaleEnabled(false);
            barChart.setEnabled(false);
            barChart.setTouchEnabled(true);
            barChart.setDragEnabled(true);
            barChart.setPinchZoom(false);
            barChart.setDrawBorders(false);//禁止绘制图表边框的线
            //隐藏图例
            Legend legend = barChart.getLegend();
            legend.setForm(Legend.LegendForm.NONE);
            barChart.zoom(0,1f,0,0);
            float ratio = (float)(dataSize)/countOnePage;
            barChart.zoom(ratio,1f,0,0);

        }
    }
    private BarChartHanlder yearBar =  new BarChartHanlder(YEAR_BAR) {
        private FlyBarChart.OnCharItemIndex onCharItemIndex = new FlyBarChart.OnCharItemIndex() {
            @Override
            public void onItemIndex(int index) {
                itemIndex = index;
                Calendar calendar = calendarHandler.startDateToNMonth(itemIndex);
                String str = String.format("%d年",calendar.get(Calendar.YEAR));
                tv_power_consumption_time.setText(str);
            }
        };

        @Override
        public void initView(int dataSize) {

            barChart.clear();
            itemIndex = 0;
            labelCount = 12;
            countOnePage = 12;
            ymin = 0;
            yMax = 500f;
            this.dataSize = dataSize;
            barWidth = computeBarWidth(pxBar,744,countOnePage);//经过调试得出该值可以使条形图宽 = 14px barWidth 约等于 14/807*12
            barChart.setOnCharItemIndex(onCharItemIndex); //设置当前项索引回调接口
            xValueFormatter = new ValueFormatter()
            {
                @Override
                public String getFormattedValue(float value)
                {

                    int IValue = (int) value %12;
                    int month = calendarHandler.startDateToNMonth(IValue).get(Calendar.MONTH) + 1;
                    if (month == 12){
                        return  month + "月";
                    }else {
                        return String.valueOf(month);
                    }

                }
            };
            yVvalueFormatter = new ValueFormatter()
            {
                @Override
                public String getFormattedValue(float value)
                {
                    barChart.initPxForOneX(countOnePage,pxBar);
                    int IValue = (int) value;
                    return String.valueOf(IValue);
                }
            };
            initX();
            initY();
            initBarChar();

            Calendar calendar = calendarHandler.startDateToNMonth(itemIndex);
            String str = String.format("%d年",calendar.get(Calendar.YEAR));
            tv_power_consumption_time.setText(str);
        }

        @Override
        public void pageNext() {
            if (itemIndex < dataSize-countOnePage) {
                Calendar calendar = calendarHandler.startDateToNMonth(itemIndex);
                int month = 12 - calendar.get(Calendar.MONTH);
                if (itemIndex + month < dataSize - countOnePage) {
                    itemIndex = month + itemIndex;
                }else{
                    itemIndex = dataSize - countOnePage;
                }
                barChart.moveViewToX(itemIndex);
                calendar = calendarHandler.startDateToNMonth(itemIndex);
                String str = String.format("%d年", calendar.get(Calendar.YEAR));
                tv_power_consumption_time.setText(str);
            }
        }

        @Override
        public void pagePrev() {
            if (itemIndex > 0) {
                int index = -1;
                Calendar calendar = calendarHandler.startDateToNMonth(itemIndex);
                int month = calendar.get(Calendar.MONTH);
                if (month == 0){
                    month = 12;
                }
                if (itemIndex - month <= 0) {
                    index = -1;
                }else{
                    index = itemIndex - month;
                }
                barChart.moveViewToX(index);
                itemIndex = index < 0 ? 0:index;
                calendar = calendarHandler.startDateToNMonth(itemIndex);
                String str = String.format("%d年",calendar.get(Calendar.YEAR));
                tv_power_consumption_time.setText(str);
            }

        }
    };

    private BarChartHanlder monthBar = new BarChartHanlder(MONTH_BAR) {
        private FlyBarChart.OnCharItemIndex onCharItemIndex = new FlyBarChart.OnCharItemIndex() {
            @Override
            public void onItemIndex(int index) {
                itemIndex = index;
                Calendar calendar = calendarHandler.startDateToNDay(itemIndex);
                String str = String.format("%d年%02d月",calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH)+1);
                tv_power_consumption_time.setText(str);
            }
        };
        @Override
        public void initView(int dataSize) {
            barChart.clear();
            itemIndex = 0;
            labelCount = 5;
            countOnePage = 31;
            ymin = 0;
            yMax = 50f;
            this.dataSize = dataSize;
            barWidth = computeBarWidth(pxBar,807,countOnePage);//经过调试得出该值可以使条形图宽 = 14px barWidth 约等于 14/807*12
            barChart.setOnCharItemIndex(onCharItemIndex); //设置当前项索引回调接口
            xValueFormatter = new ValueFormatter() {
                @Override
                public String getFormattedValue(float value)
                {
                    int IValue = (int) value;
                    Calendar calendar = calendarHandler.startDateToNDay(IValue);
                    return calendar.get(Calendar.DATE) + "日";
                }
            };
            yVvalueFormatter =new ValueFormatter() {
                @Override
                public String getFormattedValue(float value)
                {
                    barChart.initPxForOneX(countOnePage,pxBar);
                    int IValue = (int) value;
                    return String.valueOf(IValue);
                }
            };
            initX();
            initY();
            initBarChar();
            Calendar calendar = calendarHandler.startDateToNDay(itemIndex);
            String str = String.format("%d年%02d月",calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH)+1);
            tv_power_consumption_time.setText(str);
        }

        @Override
        public void pageNext() {
            if (itemIndex < dataSize-countOnePage) {

                Calendar calendar = calendarHandler.startDateToNDay(itemIndex);
                String curStr = calendarHandler.toString(calendar);
                calendar.add(Calendar.MONTH,1);

                String nextStr = String.format("%d-%02d-01",calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH)+1);
                int day = (int) calendarHandler.dateDiff(curStr,nextStr);

                if (itemIndex + day < dataSize - countOnePage) {
                    itemIndex = day + itemIndex;
                }else{
                    itemIndex = dataSize - countOnePage;
                }
                barChart.moveViewToX(itemIndex);
                calendar = calendarHandler.startDateToNDay(itemIndex);
                String str = String.format("%d年%02d月",calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH)+1);
                tv_power_consumption_time.setText(str);
                L.d(TAG,"pageNext " + calendarHandler.toString(calendarHandler.startDateToNDay(itemIndex)));
            }
        }

        @Override
        public void pagePrev() {
            if (itemIndex > 0) {
                int index = -1;
                Calendar calendar = calendarHandler.startDateToNDay(itemIndex);
                int day = calendar.get(Calendar.DAY_OF_MONTH) - 1;
                if (day == 0){
                    String curStr = calendarHandler.toString(calendar);
                    calendar.add(Calendar.MONTH,-1);
                    String nextStr = String.format("%d-%02d-01",calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH)+1);
                    day = (int) calendarHandler.dateDiff(nextStr,curStr);;
                }
                if (itemIndex - day <= 0) {
                    index = -1;
                }else{
                    index = itemIndex - day;
                }
                barChart.moveViewToX(index);
                itemIndex = index < 0 ? 0:index;
                calendar = calendarHandler.startDateToNDay(itemIndex);
                String str = String.format("%d年%02d月",calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH)+1);
                tv_power_consumption_time.setText(str);
                L.d(TAG,"pageNext " + calendarHandler.toString(calendarHandler.startDateToNDay(itemIndex)));
            }

        }
    };
    private void initMouthView() {
        curhBar = monthBar;
        String fistDate = IVehicleModule.getInstance().computeFirstDate();
        calendarHandler.init(fistDate);
        List<BarEntry> list = IVehicleModule.getInstance().getPowerConsumptionInDate();

        curhBar.initView(list.size());
        curhBar.setData(list);
        tv_power_consumption_month.setTextColor(context.getResources().getColor(R.color.colorReset));
        tv_power_consumption_year.setTextColor(context.getResources().getColor(R.color.colorWhite));
    }
    private void initYearView(){
        curhBar = yearBar;
        String fistDate = IVehicleModule.getInstance().computeFirstDate();
        calendarHandler.init(fistDate);
        List<BarEntry> list = IVehicleModule.getInstance().getPowerConsumptionInMonth();
        curhBar.initView(list.size());
        curhBar.setData(list);
        tv_power_consumption_month.setTextColor(context.getResources().getColor(R.color.colorWhite));
        tv_power_consumption_year.setTextColor(context.getResources().getColor(R.color.colorReset));
    }
}
